
"""FastAPI 封装的简单 REST 接口，方便非 MCP 客户端访问。

端点:
GET /devices -> 列出设备
GET /devices/{device_id}/alarms -> 设备告警
GET /devices/{device_id}/telemetry -> 最新遥测
GET /alarms/unconfirmed -> 未确认告警
POST /alarms/{alarm_id}/ack -> 确认告警
POST /alarms/{alarm_id}/clear -> 消除告警

运行:
    uvicorn api_server:app --host 0.0.0.0 --port 8090
或使用 run.sh http 模式。
"""
from fastapi import FastAPI, HTTPException
from thingsboard_client import ThingsBoardClient, ThingsBoardError

app = FastAPI(title="ThingsBoard Proxy API")
client = ThingsBoardClient()


@app.get("/alarms/unconfirmed")
def unconfirmed_alarms():
    try:
        alarms = client.get_unconfirmed_alarms()
        return [a.__dict__ for a in alarms]
    except ThingsBoardError as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/alarms/{alarm_id}/ack")
def acknowledge_alarm(alarm_id: str):
    try:
        client.acknowledge_alarm(alarm_id)
        return {"alarmId": alarm_id, "status": "acknowledged"}
    except ThingsBoardError as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/alarms/{alarm_id}/clear")
def clear_alarm(alarm_id: str):
    try:
        client.clear_alarm(alarm_id)
        return {"alarmId": alarm_id, "status": "cleared"}
    except ThingsBoardError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/devices")
def list_devices():
    try:
        devices = client.list_devices()
        return [d.__dict__ for d in devices]
    except ThingsBoardError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/devices/{device_id}/alarms")
def device_alarms(device_id: str):
    try:
        alarms = client.get_device_alarms(device_id)
        return [a.__dict__ for a in alarms]
    except ThingsBoardError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/devices/{device_id}/telemetry")
def device_telemetry(device_id: str):
    try:
        telemetry = client.get_latest_telemetry(device_id)
        return [t.__dict__ for t in telemetry]
    except ThingsBoardError as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8090)